# encoding: utf-8
namespace :db do
  desc "Feed locations with search names"
  task :feed_search_names => :environment do
    
    start_time = Time.now
    fail_count = 0
    succ_count = 0
    counter_text = ""
    
    # Disable logging for the 300 000 or so inserts
    # !!! Should be fixed not to disable logging globally
    old_logger = ActiveRecord::Base.logger
    ActiveRecord::Base.logger = nil
    
    Location.all.each do |loc|
      loc.search_name = loc.name.fuzzify
      if loc.save
        succ_count += 1
        STDOUT.flush
        print "\r"
        print " "*counter_text.size
        print "\r"
        counter_text = "#{succ_count} locations"
        print counter_text
      else
        puts "#{location_name} didn't save, shieeeet"
        puts loc.errors.collect(&:full_messages).join("\n")
        fail_count += 1
      end
    end
    
    end_time = Time.now
    elapsed_minutes = ((end_time - start_time)/60).floor
    elapsed_seconds = ((end_time - start_time) - elapsed_minutes*60).round
    print "\n"
    puts "Added search name for #{succ_count} locations"
    puts "#{fail_count} failed"
    puts "Took #{elapsed_minutes} #{elapsed_minutes == 1 ? "minute" : "minutes"} #{elapsed_seconds} seconds"
    
    # Enable the logging again
    ActiveRecord::Base.logger = old_logger
  end
end
